<?php

namespace Lite\Sql\Mysqli;

class MysqliResultSet implements ResultSet {
		
	/**
	 * @var mysqli_result
	 */
	private $result;
	
	function __construct(Mysqli_Result $result){
		$this->result = $result;
	}
	
	function __destruct(){
		$this->free();
	}
	
	function free(){
		if( $this->result )
			$this->result->free();
	}
	
	function getRowCount() {
		return $this->result->num_rows;
	}
	
	function getFieldCount() {
		return $this->result->field_count;
	}
	
	function getFields(){
		$fields = array();
		foreach($this->result->fetch_fields() as $field){
			$fields[] = $this->newResultRow( (array) $field);
		}
		return $fields;
	}
	
	function fetchAll($type=ResultSet::BOTH){
		$rows = array();
		
		while( ($row = $this->fetch($type)) instanceof ResultRow)
			$rows[] = $row;
		
		return $rows;
	}
	
	function fetch($type=ResultSet::BOTH){
		
		switch( $type )
		{
			case ResultSet::ASSOC:
				return $this->fetchAssoc();
			
			case ResultSet::NUM:
				return $this->fetchRow();

			case ResultSet::BOTH:
			default:
				return $this->newResultRow( $this->result->fetch_array() );	
		}
	}
	
	function fetchAssoc(){
		return $this->newResultRow( $this->result->fetch_assoc() );
	}
	
	function fetchRow(){
		return $this->newResultRow( $this->result->fetch_row() );
	}
	
	private function newResultRow($row){
		return $row ? new MysqliResultRow( $row ) : $row;
	}
	
	function getIterator(){
		return new ArrayIterator( $this->fetchAll() );
	}
}
